package com.moive.news.tqnewsapplication.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.Adapter.BaseListAdapter;
import com.moive.news.tqnewsapplication.base.BaseFragment;
import com.moive.news.tqnewsapplication.entity.UsersBean;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.ui.activity.PersonDetilsActivity;
import com.moive.news.tqnewsapplication.ui.activity.SearchActivity;
import com.moive.news.tqnewsapplication.utils.GetSystemTimeUitl;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.mylistview.SecondXListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/12/7.
 */

public class FenLeiFragment extends BaseFragment implements SecondXListView.IXListViewListener {
    @BindView(R.id.hit_query)
    EditText hitQuery;
    @BindView(R.id.pub_all_listview)
    SecondXListView pubAllListview;
    Unbinder unbinder;
    @BindView(R.id.search_text)
    TextView searchText;
    private Gson gson = new Gson();
    private int page = 1;
    private static final String TAG = "FenLeiFragment";
    private List<UsersBean.DataBean> list = new ArrayList<>();
    FeiLei02Adapter ad;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fenlei, container, false);
        view.setOnClickListener(null);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        ad = new FeiLei02Adapter(getActivity());
        pubAllListview.setAdapter(ad);
        pubAllListview.setXListViewListener(this);
        pubAllListview.setPullLoadEnable(true);
        if (TextUtils.isEmpty(PreferenceUtil.getString("token", ""))){
//            ToastUtils.ShortToast("你还未登录！无法使用此功能！");
        }else {
            getdata();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden==false){
            list.clear();
            getdata();
        }
    }

    private void getdata() {
        OkHttpUtils.post()
                .url(BaseApi.RECOMMEND_LIST)
                .addParams("token", PreferenceUtil.getString("token", ""))
                .addParams("page", page + "")
                .addParams("rows", "10")
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject1 = (JSONObject) jsonArray.opt(i);
                                UsersBean.DataBean b = gson.fromJson(jsonObject1 + "", UsersBean.DataBean.class);
                                b.setGuanzhu(false);
                                list.add(b);
                            }
                            ad.addItems(list);
                        }
                        if (jsonArray.length()==0){
//                            ToastUtils.ShortToast("没有更多数据了！");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onRefresh() {
        page = 1;
        list.clear();
        getdata();
        ad.notifyDataSetChanged();
        stopOnLoad();
    }

    private void stopOnLoad() {
        pubAllListview.stopRefresh();
        pubAllListview.stopLoadMore();
        pubAllListview.setRefreshTime(GetSystemTimeUitl.getTime());
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getdata();
                ad.notifyDataSetChanged();
                stopOnLoad();
            }
        }, 1000);
    }

    @OnClick(R.id.search_text)
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.search_text:
                String s=hitQuery.getText().toString().trim();
                if (TextUtils.isEmpty(s)){
                    ToastUtils.ShortToast("请输入添加好友昵称！");
                    return;
                }else {
                    Intent intent=new Intent(getActivity(), SearchActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("title",s);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                break;
        }
    }

    public class FeiLei02Adapter extends BaseListAdapter<UsersBean.DataBean> {
        private Context context;
        public FeiLei02Adapter(Context context) {
            this.context = context;
        }

        @Override
        protected View getItemView(int position, View convertView, ViewGroup parent, List<UsersBean.DataBean> item) {
            ViewHeolder viewHeolder = null;
            if (viewHeolder == null) {
                viewHeolder = new ViewHeolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.adapter_fenlei02, null);
                viewHeolder.fenlei02_img = convertView.findViewById(R.id.fenlei02_img);
                viewHeolder.fenlei02_name = convertView.findViewById(R.id.fenlei02_name);
                viewHeolder.fenlei02_time = convertView.findViewById(R.id.fenlei02_time);
                viewHeolder.fenlei02_guanzhu_number = convertView.findViewById(R.id.fenlei02_guanzhu_number);
                viewHeolder.fenlei02_guanzhu = convertView.findViewById(R.id.fenlei02_guanzhu);
                convertView.setTag(viewHeolder);
            } else {
                viewHeolder = (ViewHeolder) convertView.getTag();
            }
            viewHeolder.fenlei02_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(getActivity(), PersonDetilsActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putString("id",item.get(position).getId());
                    bundle.putString("user_img",item.get(position).getHeadimg());
                    bundle.putString("user_name",item.get(position).getNickname());
                    bundle.putBoolean("isguanzhu",item.get(position).isGuanzhu());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            Glide.with(context)
                    .load(item.get(position).getHeadimg())
                    .centerCrop()
                    .dontAnimate()
                    .placeholder(R.drawable.icon)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(viewHeolder.fenlei02_img);
            viewHeolder.fenlei02_name.setText(item.get(position).getNickname());
            if (TextUtils.isEmpty(item.get(position).getSignature())){
                viewHeolder.fenlei02_time.setText("TA不想介绍自己！");
            }
            final ViewHeolder finalViewHolder1 = viewHeolder;
            viewHeolder.fenlei02_guanzhu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (TextUtils.isEmpty(PreferenceUtil.getString("token",""))){
                        ToastUtils.ShortToast("你还未登录，请登录后在使用此功能！");
                    }else {
                        if (list.get(position).isGuanzhu()==false) {
                            gguanzhu(finalViewHolder1, item.get(position).getId(),position);
                        } else {
                            delteguanzhu(finalViewHolder1, item.get(position).getId(),position);
                        }
                    }
                }
            });
            return convertView;
        }

        class ViewHeolder {
            CircleImageView fenlei02_img;
            TextView fenlei02_name, fenlei02_time, fenlei02_guanzhu_number;
            ImageView fenlei02_guanzhu;
        }

        //加关注
        private void gguanzhu(final ViewHeolder viewHolder, String followID,int postion) {
            OkHttpUtils.post()
                    .url(BaseApi.GUANZHU_ONE)
                    .addParams("token", PreferenceUtil.getString("token", ""))
                    .addParams("followID", followID)
                    .build().execute(new OkManagerCallback(getActivity()) {
                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                    LogUtil.e(TAG, e.toString());
                }
                @Override
                public void onResponse(String response, int id) {
                    super.onResponse(response, id);
                    LogUtil.i(TAG, response.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optInt("code") == 0) {
                            viewHolder.fenlei02_guanzhu.setBackgroundResource(R.drawable.fenlei02_guanzhu02);
                            list.get(postion).setGuanzhu(true);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        //取消关注
        private void delteguanzhu(final ViewHeolder viewHolder, String followID,int postion) {
            OkHttpUtils.post()
                    .url(BaseApi.UN_GUANZHU)
                    .addParams("token", PreferenceUtil.getString("token", ""))
                    .addParams("followID", followID)
                    .build().execute(new OkManagerCallback(getActivity()) {
                @Override
                public void onError(Call call, Exception e, int id) {
                    super.onError(call, e, id);
                    LogUtil.e(TAG, e.toString());
                }

                @Override
                public void onResponse(String response, int id) {
                    super.onResponse(response, id);
                    LogUtil.i(TAG, response.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optInt("code") == 0) {
                            viewHolder.fenlei02_guanzhu.setBackgroundResource(R.drawable.fenlei02_guanzhu01);
                          list.get(postion).setGuanzhu(false);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
